package com.wyq.gulimall.service.impl;



import com.alibaba.fastjson.JSON;
import com.wyq.gulimall.common.vo.SkuEsModel;
import com.wyq.gulimall.config.ElasticSearchConfig;
import com.wyq.gulimall.constant.ESConstant.EsConstant;
import com.wyq.gulimall.service.ProductSaveService;
import lombok.extern.log4j.Log4j2;
import netscape.javascript.JSObject;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wangy
 * @version 1.0
 * @description: TODO
 */
@Log4j2
@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) {
        // 保存到es中
        //1、给es中建立索引。product，建立好映射关系。
        //2、给es中保存这些数据
        //BulkRequest bulkRequest, RequestOptions options
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel model : skuEsModels) {
            // 构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            //指定数据id
            indexRequest.id(model.getSkuId().toString());
            //将要保存的数据对象转换为JSON格式
            String s = JSON.toJSONString(model);

            //插入数据 并指明数据类型为JSON
            indexRequest.source(s, XContentType.JSON);
            //将保存请求(indexRequest)添加到批量保存请求中
            bulkRequest.add(indexRequest);
        }
        //创建批量执行对象
        //使用restHighLevelClient客户端进行保存 拿到响应结果
        //两个参数 第一个是批量保存的请求 第二个是请求OPTIONS
        BulkResponse bulk = null;
        try {
            bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //分析保存结果
        boolean b = bulk.hasFailures();
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("商品上架成功: {}", collect);
        //返回布尔类型的数据，如果是true就是有错误了，返回false就是没有错误
        return b;
    }
}
